//
//  GuanliViewController.swift
//  联付商圈
//
//  Created by zhangqi on 2017/7/21.
//  Copyright © 2017年 lianfu. All rights reserved.
//

import UIKit
import Alamofire
//typealias sendValueClosure=(_ password:String)->Void
@objc class GuanliViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {

    var delegate: PassDataDelegate!
    //var testClosure:sendValueClosure?
    //var kaArray = ["储值卡（尾号1234）","储值卡（尾号4321）"]
    var cardDic = [[String:Any]]()
    //let CYView = CYPasswordView()
     //var aa:CYView.finish
    @IBAction func push(_ sender: UIBarButtonItem) {
        self.navigationController?.pushViewController(BoundBankCardViewController(), animated: true)
    }
    
    
    @IBOutlet weak var GuanliTableView: UITableView!
    

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        GuanliTableView.tableFooterView = UIView(frame: CGRect.zero)
        showcards()
//        let keyWindow = UIApplication.shared.keyWindow!
//        CYView.show(in: keyWindow)
//        CYView.finish = {
//            password -> Void in
//            let x = password as String!
//            print(x!)
//            self.CYView.hide()
//            }
        
        
        // 通知
//        NSString *const CYPasswordViewCancleButtonClickNotification = @"CYPasswordViewCancleButtonClickNotification";
//        NSString *const CYPasswordViewDeleteButtonClickNotification = @"CYPasswordViewDeleteButtonClickNotification";
//        NSString *const CYPasswordViewNumberButtonClickNotification = @"CYPasswordViewNumberButtonClickNotification";
//        NSString *const CYPasswordViewForgetPWDButtonClickNotification = @"CYPasswordViewForgetPWDButtonClickNotification";
//        NSString *const CYPasswordViewEnabledUserInteractionNotification = @"CYPasswordViewEnabledUserInteractionNotification";
//        NSString *const CYPasswordViewDisEnabledUserInteractionNotification = @"CYPasswordViewDisEnabledUserInteractionNotification";
//        NotificationCenter.default.addObserver(self, selector: #selector(forget), name: NSNotification.Name.CYPasswordViewForgetPWDButtonClick, object: nil)
//        NotificationCenter.default.addObserver(self, selector: #selector(cancel), name: NSNotification.Name.CYPasswordViewCancleButtonClick, object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    
    
    func showcards(){
        let x = UserDefaults.standard.object(forKey: "userInfo") as! NSDictionary
        //print(x)
        let y = x["name"]!
        let parameters = ["name":"\(y)"]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/showbank?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: parameters).responseJSON {Request in
            switch Request.result {
            case .success:
                let json = JSON(data: Request.data!)
                self.cardDic = json.arrayObject as! [[String : Any]]
                //print(json)
                self.GuanliTableView.reloadData()
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }
    
    func delcard(id:String){
        let parameters = ["id":id]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/delbank?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: parameters).responseJSON {Request in
            switch Request.result {
            case .success:
                self.showcards()
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return cardDic.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "GuanliTableViewCell", for: indexPath) as! GuanliTableViewCell
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        let x = "\(cardDic[indexPath.row]["type"]!)"
        let y = "\(cardDic[indexPath.row]["BankCardNumber"]!)"
        
        
        
        let startIndex = y.index(y.startIndex, offsetBy: y.lengthOfBytes(using: .utf8) - 4)
        let endIndex = y.index(startIndex, offsetBy:4)
        let result = y.substring(with: startIndex..<endIndex)
        cell.label.text = x + result
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headTitle: UILabel = UILabel()
        headTitle.backgroundColor = UIColor.clear
        return headTitle
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 12
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        GuanliTableView.deselectRow(at: indexPath, animated: false)
        if guanliORtixian == "guanli" {
            return
        } else if guanliORtixian == "tixian" {
            if delegate != nil {
                let x = cardDic[indexPath.row] as NSDictionary
                delegate.setControllerTitle(text: x)
            }
            navigationController?.popViewController(animated: true)
        } else {
            return
        }
        
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return UITableViewCellEditingStyle.delete
    }
    
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "解除绑定"
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        
        if editingStyle == UITableViewCellEditingStyle.delete {
            let x = "\(cardDic[indexPath.row]["id"]!)"
            delcard(id:x)
        }
    }
}
